package com.general.client.widgets.autopositionpanel;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Widget;

public class PositioningLogic {
	public class Position {
		public int absX, absY;
		public VerticalPosition verticalPosition;

		public Position() {
		}

		public Position(int absX, int absY, VerticalPosition verticalPosition) {
			super();
			this.absX = absX;
			this.absY = absY;
			this.verticalPosition = verticalPosition;
		}

	}

	public enum VerticalPosition {
		ABOVE, BELOW;
	}

	public Position getPosition(Widget relocatableWidget, Widget relativeToWidget, int verticalShift,
			int horizontalShift, VerticalPosition defaultVerticalPosition) {
		Position result = new Position();
		int offsetHeight = relocatableWidget.getOffsetHeight();
		int offsetWidth = relocatableWidget.getOffsetWidth();
		int bottom = relativeToWidget.getElement().getAbsoluteBottom();
		int top = relativeToWidget.getElement().getAbsoluteTop();
		int left = relativeToWidget.getElement().getAbsoluteLeft();
		int windowWidth = Window.getClientWidth();
		int windowHeight = Window.getClientHeight();
		int x, y;
		y = top;
		result.verticalPosition = VerticalPosition.ABOVE;
		boolean verticalPositionFound = false;

		if (top - offsetHeight - verticalShift >= 0) {
			y = top - offsetHeight - verticalShift;
			result.verticalPosition = VerticalPosition.ABOVE;
			verticalPositionFound = true;
		}
		if ((defaultVerticalPosition.equals(VerticalPosition.BELOW) || !verticalPositionFound)
				&& bottom + offsetHeight + verticalShift <= windowHeight) {
			y = bottom + verticalShift;
			result.verticalPosition = VerticalPosition.BELOW;
			verticalPositionFound = true;
		}
		result.absY = y;
		x = left - horizontalShift;
		int moveL = x + offsetWidth + horizontalShift - windowWidth;
		if (moveL > 0)
			x = x - moveL;
		int moveR = x - horizontalShift;
		if (moveR < 0)
			x = x - moveR;
		result.absX = x;
		return result;
	}
}
